package com.ziyun.pop.web.modules.goods.controller;

import com.netflix.discovery.converters.Auto;
import com.service.goods.api.GoodsService;
import com.service.goods.constant.GoodsResult;
import com.service.model.quote.constant.AttributeValueType;
import com.service.model.quote.constant.OemCategoryType;
import com.service.quote.module.factory.model.FactoryQuoteInfo;
import com.service.quote.module.quote.model.QuoteDto;
import com.service.quote.module.quote.model.QuoteResult;
import com.utility.JsonUtils;
import com.utility.New;
import com.utility.StringUtils;
import com.utility.http.HttpUtils;
import com.ziyun.pop.common.utils.UserUtils;
import com.ziyun.pop.modules.goods.TwbVo.TwbEditPriceVo;
import com.ziyun.pop.modules.goods.TwbVo.TwbGoodsVo;
import com.ziyun.pop.modules.goods.dto.CountQuoteDto;
import com.ziyun.pop.modules.goods.entity.GoodsEntity;
import com.ziyun.pop.modules.goods.vo.FastPriceVo;
import com.ziyun.pop.modules.goods.vo.PrintPriceVo;
import com.ziyun.pop.modules.goods.vo.QuoteVO;
import com.ziyun.pop.modules.goods.vo.VerifyPriceVo;
import com.ziyun.pop.modules.storeGoodsCategory.service.StoreGoodsCategoryService;
import com.ziyun.pop.modules.supp.service.SellerInfoService;
import io.renren.common.utils.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 商品表
 *
 * @author
 * @email
 * @date 2018-08-21 08:46:29
 */
@RestController
@RequestMapping("goods/goods")
public class GoodsController {


    @Value("${erpApi}")
    private String erpApi ;

    @Autowired
    private StoreGoodsCategoryService storeGoodsCategoryService;

    @Autowired
    private com.ziyun.pop.modules.goods.service.GoodsService goodsService2;

    @Autowired
    private GoodsService goodsService;


    /**
     * 列表
     */
    @RequestMapping("/list")
    // @RequiresPermissions("goods:goods:list")
    public R list( @RequestParam Map<String, Object> params){
        params.put("sellerId",UserUtils.getCurentUser().getSellerId());
        // 远程调用
        String url = erpApi + "/goods/goods/list";
        Map<String, Object> paramHeaderMap = New.hashMap();
        Map<String, Object> paramBodyMap = New.hashMap();
        paramBodyMap.put("params", params);
        // 商品列表远程调用
        String response = HttpUtils.doPost(url, paramHeaderMap, JsonUtils.map2String(paramBodyMap));
        System.out.println(response);
        Map<String, Object> map = com.ziyun.pop.common.utils.JsonUtils.jsonToMap(response);
        return R.ok().put("page", map.get("page"));
    }
    /**
     * 信息
     */
    @RequestMapping("/info/{goodsId}")
//    @RequiresPermissions("goods:goods:info")
    public R info(@PathVariable("goodsId") Long goodsId){
        String url = erpApi + "/goods/goods/info";
        Map<String, Object> paramHeaderMap = New.hashMap();
        Map<String, Object> paramBodyMap = New.hashMap();
        paramBodyMap.put("goodsId", goodsId);
        paramBodyMap.put("sellerId",UserUtils.getCurentUser().getSellerId());
        String response = HttpUtils.doPost(url, paramHeaderMap, JsonUtils.map2String(paramBodyMap));
        Map<String, Object> map = com.ziyun.pop.common.utils.JsonUtils.jsonToMap(response);
        return R.ok().put("goods", map.get("goods")).put("goodsProductList",map.get("goodsProductList")).put("designGood",map.get("designGood"))
                .put("imageList",map.get("imageList")).put("infoList",map.get("infoList")).put("videoEntity",map.get("videoEntity")).put("attributeAndCraftData",map.get("attributeAndCraftData"))
                .put("allQuoteTemplate",map.get("allQuoteTemplate")).put("goodsTemplateEntity",map.get("goodsTemplateEntity"))
                .put("unitLibraryList",map.get("unitLibraryList"));
    }
    /**
     * 修改--编辑商品保存
     */
    @RequestMapping("/update")
    //@RequiresPermissions("goods:goods:update")
    public R update(@RequestBody GoodsEntity goods){
        if(goods.getExamineStatus().intValue() == 2){
            //如果是审核失败的商品,重新编辑后将状态置为待审核
            goods.setExamineStatus(0);
        }
        Map<String, Object> params = New.hashMap();
        params.put("goods",goods);
        params.put("userId",UserUtils.getCurentUser().getUserId());
        String path = "/goods/goods/update";
        Map<String, Object> resultMap = remoteProcedureCall(params, path);
//        goodsService.updateGoods(goods);//全部更新
        return R.ok();
    }
//    /**
//     * 删除
//     */
//    @RequestMapping("/delete")
//    //@RequiresPermissions("goods:goods:delete")
//    public R delete(@RequestBody Long[] goodsIds){
//        goodsService.deleteBatchIds(Arrays.asList(goodsIds));
//        return R.ok();
//    }
    /**
     * 查询设计服务商品
     */
    @RequestMapping("/designList")
    public R designList( @RequestParam Map<String, Object> params){
        String path = "/goods/goods/designList";
        Map<String, Object> map = remoteProcedureCall(params,path);
        System.out.println("page:"+map.get("page"));
//        PageUtils page = goodsService.queryPageNew(params);
        return R.ok().put("page", map.get("page"));
    }


    /**
     * 商品关联设计服务
     */
    @RequestMapping("/addDesign/{goodId}/{designId}")
    public R addDesign(@PathVariable("goodId")String goodId,@PathVariable("designId")String designId){
        String url = erpApi + "/goods/goods/addDesign";
        Map<String, Object> paramHeaderMap = New.hashMap();
        Map<String, Object> paramBodyMap = New.hashMap();
        paramBodyMap.put("goodsId",Integer.parseInt(goodId));
        paramBodyMap.put("goodsId",Integer.parseInt(designId));
        String response = HttpUtils.doPost(url, paramHeaderMap, JsonUtils.map2String(paramBodyMap));
        Map<String, Object> map = com.ziyun.pop.common.utils.JsonUtils.jsonToMap(response);
//        Integer nGoodId = StringUtil.getRequestParamInteger(goodId);
//        Integer nGesignId = StringUtil.getRequestParamInteger(designId);
//        goodsService.addDesign(nGoodId,nGesignId);
        return R.ok();
    }

    /**
     * 发布商品
     */
    @RequestMapping("/pushGood")
    public R pushGood(@RequestBody GoodsEntity goods){
        goods.setSelf(false);
        goods.setSellerId(UserUtils.getCurentUser().getSellerId().intValue());
        goods.setCreateName(UserUtils.getCurentUser().getUsername());
        String path = "/goods/goods/pushGood";
        Map<String, Object> map = New.hashMap();
        map.put("goods",goods);
        remoteProcedureCall(map,path);
        return R.ok();
    }
    /**
     * updateStatus更新spu状态
     */
    @RequestMapping("/updateStatus/{goodsId}/{status}")
    public R updateStatus(@PathVariable("goodsId")Long goodsId,@PathVariable("status")String status){
        Map<String, Object> map = New.hashMap();
        map.put("goodsId",goodsId);
        map.put("status",status);
        map.put("userId",UserUtils.getCurentUser().getUserId());
        String path = "/goods/goods/updateStatus";
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
//        goodsService.updateStatus(goodsId,status);
        return R.ok();
    }
//
    /**
     * 发布商品
     */
    @RequestMapping("/pushQuoteGood")
    public R pushQuoteGood(@RequestBody QuoteVO quoteVO){
        System.out.println(quoteVO);
        quoteVO.getGoodsEntity().setSelf(false);
        quoteVO.getGoodsEntity().setSellerId(Integer.parseInt(UserUtils.getCurentUser().getSellerId().toString()));
        quoteVO.getGoodsEntity().setCreateName(UserUtils.getCurentUser().getUsername());
        for(int i = 0;i<quoteVO.getQuoteProductBaseInfoVOList().size();i++){
            quoteVO.getQuoteProductBaseInfoVOList().get(i).setCreateUser(UserUtils.getCurentUser().getUsername());
        }
//        goodsService.pushQuoteGood(quoteVO);
        String path = "/goods/goods/pushQuoteGood";
        Map<String, Object> map = New.hashMap();
        map.put("quoteVO",quoteVO);
        remoteProcedureCall(map,path);
        return R.ok();
    }

    /**
     *
     */
    @RequestMapping("/countPrice")
    public R countPrice(@RequestBody List<Map<String,Object>> list){
        String path = "/goodsCategory/goodscategory/countPrice";
        List<Map<String,Object>> resultList = new ArrayList<>();
        Boolean erpSellerFlag = (Boolean) list.get(0).get("erpSellerFlag");
        Integer categoryId1 = Integer.valueOf(String.valueOf(list.get(0).get("categoryId")));
        for(int i = 0;i<list.size();i++){
            Integer partsId = (Integer) list.get(i).get("partsId");
            List ids = (List) list.get(i).get("ids");
            //根据ids去查询获得
            Map<String, Object> map = New.hashMap();
            if(list.size() != 1){
                map.put("partsId",partsId);
            }else{
                map.put("categoryId",partsId);
            }
            map.put("ids", org.apache.commons.lang.StringUtils.join(ids,","));
            Map<String, Object> resultMap = remoteProcedureCall(map, path);
            Map map1 = (Map) resultMap.get("map");
            Boolean flag = (Boolean) map1.get("flag");
            if(flag){
                resultList.add(resultMap);
            }
        }
        QuoteDto quoteDto = new QuoteDto();
        Map map2 = (Map) resultList.get(0).get("map");
        String categoryType = (String) map2.get("categoryType");
        OemCategoryType oemCategoryType = OemCategoryType.valueOf(categoryType);
        quoteDto.setCategoryType(oemCategoryType);
        //处理数据
        Map<Integer, Map> newAttributesMap = New.hashMap();
        Map<Integer, Map<AttributeValueType, Integer>> lastAttributesMap = New.hashMap();
        for(int i = 0;i<resultList.size();i++){
            //map1是一个部件返回的数据信息
            Map map1 = (Map) resultList.get(i).get("map");
            Map attributesMap = (Map) map1.get("attributesMap");
            List list1 = (List) attributesMap.get("list");
            Integer categoryId = (Integer) attributesMap.get("categoryId");
            Map<String, Object> temp = New.hashMap();
            Map<AttributeValueType, Integer> newTemp = New.hashMap();
            for(int j = 0;j<list1.size();j++){
                Map map = (Map) list1.get(j);
                Integer optionId = (Integer) map.get("optionId");
                String attributeValueKey = (String) map.get("attributeTypeValue");
                temp.put(attributeValueKey,optionId);
                AttributeValueType attributeValueType = AttributeValueType.valueOf(attributeValueKey);
                newTemp.put(attributeValueType,optionId);
            }
            newAttributesMap.put(categoryId,temp);
            lastAttributesMap.put(categoryId,newTemp);
        }
        quoteDto.setAttributesMap(lastAttributesMap);
//        quoteDto.setErpSellerFlag(erpSellerFlag);
        quoteDto.setErpSellerFlag(true);
        quoteDto.setCategoryId(categoryId1);
        quoteDto.setFactoryId(UserUtils.getCurentUser().getSellerId());
        System.out.println(JsonUtils.object2String(quoteDto));
        GoodsResult<QuoteResult> factoryQuote = goodsService.findFactoryQuote(quoteDto);
        if(factoryQuote != null){
            if(factoryQuote.getData() != null){
                List<FactoryQuoteInfo> factoryQuoteInfos = factoryQuote.getData().getFactoryQuoteInfos();
                if(factoryQuoteInfos.size() > 0){
                    if(factoryQuoteInfos.size() > 1){
                        return R.error("异常信息,默认商品算价找到多个工厂!");
                    }
                    Double totalPrice = factoryQuoteInfos.get(0).getTotalPrice();
                    return R.ok().put("result",totalPrice);
                }else{
                    return R.ok().put("result","默认商品算价没有找到工厂");
                }
            }else{
                return R.ok().put("result", "默认商品算价没有找到工厂");
            }
        }
        return R.error("默认商品算价回调返回值为空");
    }
    /**
     * 信息
     */
    @RequestMapping("/designInfo/{designId}")
//    @RequiresPermissions("goods:goods:info")
    public R designInfo(@PathVariable("designId") Long designId){
        String path ="/goods/goods/designInfo";
        Map<String, Object> map = New.hashMap();
        map.put("designId",designId);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok().put("designGood",resultMap.get("designGood"));
    }

    /**
     * 根据分类获得所有模板表数据
     */
    @RequestMapping("/quoteTemplate/{categoryId}")
    public R getQuoteTemplate(@PathVariable("categoryId") String categoryId){
        String path = "/goods/goods/quoteTemplate";
        Map<String, Object> map = New.hashMap();
        map.put("categoryId",categoryId);
        map.put("factoryId",UserUtils.getCurentUser().getSellerId());
        //Integer factoryId
//        List<Map> allQuoteTemplate = quoteProductBaseInfoService.getAllQuoteTemplate(requestParamInteger);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        //获得sellerId是小b还是工厂
//        String type = storeGoodsCategoryService.getSellerType(UserUtils.getCurentUser().getSellerId());


        return R.ok().put("allQuoteTemplate",resultMap.get("allQuoteTemplate"));
    }

    /**
     *工艺校验价格
     */
    @RequestMapping("/verifyCraftPrice")
    public R verifyCraftPrice(@RequestBody VerifyPriceVo verifyPriceVo){
//        System.out.println(verifyPriceVo);
        String path = "/goods/goods/verifyCraftPrice";
        Map<String, Object> map = New.hashMap();
        map.put("verifyPriceVo",verifyPriceVo);
        map.put("sellerId",UserUtils.getCurentUser().getSellerId());
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
//        String result = goodsService.verifyCraftPrice(verifyPriceVo);
        return R.ok().put("msg",resultMap.get("result"));
    }

    /**
     *工艺校验价格
     */
    @RequestMapping("/quotePrice")
    public R quotePrice(@RequestBody String ids){
//        System.out.println(ids);
        String path = "/goods/goods/quotePrice";
        Map<String, Object> map = New.hashMap();
        map.put("ids",ids);
        map.put("sellerId",UserUtils.getCurentUser().getSellerId());
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
//        String result = goodsService.quotePrice(ids,1);
        return R.ok().put("result",resultMap.get("result"));
    }

    /**
     *商务印刷机器校验
     */
    @RequestMapping("/verifyPrintPrice")
    public R verifyPrintPrice(@RequestBody PrintPriceVo printPriceVo){
        String path = "/goods/goods/verifyPrintPrice";
        Map<String, Object> map = New.hashMap();
        map.put("printPriceVo",printPriceVo);
        map.put("factoryId",UserUtils.getCurentUser().getSellerId());
//        Integer factoryId = 1;
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
//        String result = goodsService.verifyPrintPrice(printPriceVo,factoryId);
        return R.ok().put("result",resultMap.get("result"));
    }

    /**
     * 数码快印组合商品计价校验
     */
    @RequestMapping("/verifyFastPrice")
    public R verifyFastPrice(@RequestBody List<FastPriceVo> fastPriceVoList){
        String path = "/goods/goods/verifyFastPrice";
        Map<String, Object> map = New.hashMap();
        map.put("fastPriceVoList",fastPriceVoList);
        map.put("sellerId",UserUtils.getCurentUser().getSellerId());
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
//        Integer sellerId = 1;
//        String result = goodsService.verifyFastPrice(fastPriceVoList,sellerId);
        return R.ok().put("result",resultMap.get("result"));
    }

    /**
     * 发布商品
     */
    @RequestMapping("/updateQuoteGood")
    public R updateQuoteGood(@RequestBody QuoteVO quoteVO){
        if(quoteVO.getGoodsEntity().getExamineStatus().intValue() == 2){
            quoteVO.getGoodsEntity().setExamineStatus(0);
        }
        String path = "/goods/goods/updateQuoteGood";
        Map<String, Object> map = New.hashMap();
        map.put("quoteVO",quoteVO);
        map.put("sellerId",UserUtils.getCurentUser().getSellerId());
        map.put("username",UserUtils.getCurentUser().getUsername());
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok();
    }

    /**
     * 改变商品审核状态
     */
    @RequestMapping("/examineGoods/{goodsId}/{examine}")
    public R examineGoods(@PathVariable("goodsId")Integer goodsId,@PathVariable("examine")Integer examine){
        String path = "/goods/goods/examineGoods";
        Map<String, Object> map = New.hashMap();
        map.put("goodsId",goodsId);
        map.put("examine",examine);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
//        goodsService.examineGoods(goodsId,examine);
        return R.ok().put("result",resultMap.get("result"));
    }

    /**
     * twb发布商品第二部,根据spu获得商品信息
     */
    @RequestMapping("/getGoodsByGoodsIds")
    public R getGoodsByGoodsIds(@RequestBody List<Integer> goodsIds){
        //先初始化商户工艺价和运费模板信息

        R r = goodsService2.copyGoodsCraftPriceTemplate(UserUtils.getCurentUser().getSellerId(), 1L);
        Integer freightId = (Integer) r.get("freightId");
        String path = "/goods/goods/getGoodsByGoodsIds";
        Map<String, Object> map = New.hashMap();
        map.put("goodsIds",goodsIds);
        map.put("freightId",freightId);
        try{
            Map<String, Object> resultMap = remoteProcedureCall(map, path);
            return R.ok().put("goodsChoiceList",resultMap.get("twbGoodsVoList"));
        }catch (Exception e){
            e.printStackTrace();
            return R.error("发布商品第二步骤接口调用异常!");
        }
    }

    /**
     * 信息
     */
    @RequestMapping("/getTwbGoodsInfo/{goodsId}")
    //    @RequiresPermissions("goods:goods:info")
    public R getTwbGoodsInfo(@PathVariable("goodsId") Long goodsId){
        String path ="/goods/goods/getTwbGoodsInfo";
        Map<String, Object> map = New.hashMap();
        map.put("goodsId",goodsId);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok().put("twbGoodsVo",resultMap.get("twbGoodsVo"));
    }

    /**
     *获得单位库数据信息
     */
    @RequestMapping("/getUnitLibrary")
    public R getUnitLibrary(){
        String path ="/goods/goods/getUnitLibrary";
        Map<String, Object> map = New.hashMap();
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok().put("unitLibraryList",resultMap.get("unitLibraryList"));
    }

    /**
     *图文宝批量发布商品
     */
    @RequestMapping("/twbListPushGoods/{pushMark}")
    public R twbListPushGoods(@RequestBody List<TwbGoodsVo> twbGoodsVoList,@PathVariable("pushMark") Boolean pushMark){
        String path ="/goods/goods/twbListPushGoods";
        Map<String, Object> map = New.hashMap();
        map.put("twbGoodsVoList",twbGoodsVoList);
        map.put("userName",UserUtils.getCurentUser().getUsername());
        map.put("sellerId",UserUtils.getCurentUser().getSellerId());
        map.put("pushMark",pushMark);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok();
    }

    /**
     *图文宝商品列表
     */
    @RequestMapping("/getTwbGoodsList")
    public R getTwbGoodsList(@RequestBody Map params){
        String path ="/goods/goods/getTwbGoodsList";
        Map<String, Object> map = New.hashMap();
        map.put("sellerId",UserUtils.getCurentUser().getSellerId());
        map.put("marketable",params.get("marketable"));
        map.put("current",params.get("current"));
        map.put("size",params.get("size"));
        map.put("total",params.get("total"));
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok().put("goodsEntityPage",resultMap.get("goodsEntityPage"));
    }

    /**
     * 编辑价格获取信息
     */
    @RequestMapping("/editTwbGoodsPrice/{goodsId}")
    public R editTwbGoodsPrice(@PathVariable("goodsId") Long goodsId){
        String path ="/goods/goods/editTwbGoodsPrice";
        Map<String, Object> map = New.hashMap();
        map.put("goodsId",goodsId);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok().put("twbEditPriceVoList",resultMap.get("twbEditPriceVoList"));
    }

    /**
     *图文宝商品列表
     */
    @RequestMapping("/saveTwbEditPrice")
    public R saveTwbEditPrice(@RequestBody List<TwbEditPriceVo> twbEditPriceVoList){
        String path ="/goods/goods/saveTwbEditPrice";
        Map<String, Object> map = New.hashMap();
        map.put("twbEditPriceVoList",twbEditPriceVoList);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok();
    }

    /**
     * 发布商品第一步前,加载图文宝分类列表和商品
     */
    @RequestMapping("/getTwbCateAndGoods")
    public R getTwbCateAndGoods(){
        String path ="/goods/goods/getTwbCateAndGoods";
        Map<String, Object> map = New.hashMap();
        map.put("sellerId",UserUtils.getCurentUser().getSellerId());
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok().put("resultMap",resultMap.get("resultMap"));
    }

    /**
     * 图文宝列表批量处理商品状态
     */
    @RequestMapping("/twbListOperation/{marketable}")
    public R twbListOperation(@RequestBody List<Integer> goodIdList,@PathVariable String marketable){
        String path ="/goods/goods/twbListOperation";
        Map<String, Object> map = New.hashMap();
        map.put("goodIdList",goodIdList);
        System.out.println(goodIdList.toString());
        map.put("marketable",marketable);
        Map<String, Object> resultMap = remoteProcedureCall(map, path);
        return R.ok();
    }

    /**
     * 远程调用方法封装
     * @param params
     * @return
     */
    private Map<String, Object> remoteProcedureCall(@RequestParam Map<String, Object> params,String path) {
        String url = erpApi + path;
        Map<String, Object> paramHeaderMap = New.hashMap();
        Map<String, Object> paramBodyMap = New.hashMap();
        paramBodyMap.put("params",params);
        String response = HttpUtils.doPost(url, paramHeaderMap, JsonUtils.map2String(paramBodyMap));
        return com.ziyun.pop.common.utils.JsonUtils.jsonToMap(response);
    }
}
